import { Menu, Dropdown, Icon,Button ,Calendar,Input,Row,Col,Checkbox ,Tree  } from 'antd';
const TreeNode = Tree.TreeNode;
const Item = Menu.Item;
const CheckboxGroup = Checkbox.Group;
import {WeaTools} from 'ecCom'
import Immutable from 'immutable'
const is = Immutable.is;

import './style/index.css';

class WeaDropdown extends React.Component {
    constructor(props) {
		super(props);
        this.state={
            value:"",
            visible:false,
            thisyear:new Date().getFullYear(),
            hrmDatas:props.datas || [],
            num:1,
            checkArr:[]
        }
	}
    componentWillReceiveProps(nextProps) {
        if(!is(this.props.datas,nextProps.datas)){
            this.setState({hrmDatas:nextProps.datas})
        }
    }
	render() {
		const {value,checkArr} = this.state;
        const dateMonth= [
            [{m:1},{m:2},{m:3}],
            [{m:4},{m:5},{m:6}],
            [{m:7},{m:8},{m:9}],
            [{m:10},{m:11},{m:12}]];
        const {datas,defaultValue,type,keyValue,selectKeys = "",hrmListChange} = this.props;
        let menu = "";
        if(type=="time"){
            menu = <Menu >
                      <Item key="crm-calendar-header">
                            <div style={{textAlign:"center",width:"120px"}}>
                                <div className="crm-calendar-header-left" onClick={this.decYear}><Icon type="left" /></div>
                                 <span className="crm-calendar-header-center">{this.state.thisyear}</span>
                                 <div className="crm-calendar-header-right" onClick={this.addYear}><Icon type="right" /></div>
                            </div>
                      </Item>
                      <Item key="calendar-body" className="crm-calendar-body">
                            {
                                dateMonth.map((item,index) =>{
                                    return (
                                         <Row key={index}>
                                            {
                                                item.map((mon,index)=>{
                                                    return (<Col span={8} onClick={()=>{this.callBackMonth(mon.m)}}>{mon.m}</Col>)
                                                })
                                            }
                                         </Row>
                                    )
                                })
                            }
                      </Item>
                      <Item key="calendar-footer" className="crm-calendar-footer"><div onClick={this.callBackMonthAll}>全部</div></Item>
                 </Menu>
        }else if(type=="select"){
            menu = <Menu onClick={this.onSelectChange.bind(this)}>
                  {
                    datas.map(function(data,index) {
                        return (
                            <Item key={`item${data.id}`}  >
                                {data.name}
                            </Item>
                        )
                    })
                }
                </Menu>
        }else if(type=="tag"){
            const me = this;
             menu = <Menu onClick={this.onMenuClick.bind(this)}>
                    <Item key="important" disabled={!selectKeys}>重要</Item>
                    <Item key="unimportant" disabled={!selectKeys}>取消重要</Item>
                    <Menu.Divider />
                  {
                    datas.map(function(data,index) {
                        return (
                            <Item key={data.key}>
                               <Checkbox onChange={()=>me.checkboxChange(data.key)}>
                                    <span style={{color:`${data.textColor}`,backgroundColor:`${data.labelColor}`,padding:"0 3px"}}>{data.title}</span>
                               </Checkbox> 
                            </Item>
                        )
                    })
                  }
                  <Item key="setting">
                        <div className="crm-tag-setting-footer " >
                            <Button type="primary" size="small" disabled = {!(selectKeys && `${checkArr}`)} onClick={()=>this.markLable("addLabel")}>应用</Button>
                            <Button type="ghost" size="small" disabled = {!(selectKeys && `${checkArr}`)} onClick={()=>this.markLable("cancelLabel")}>取消</Button>
                            <Button type="primary" size="small" onClick={this.setting}>设置</Button>
                        </div>
                  </Item>
                </Menu>
        }else if(type== "tree"){
            const me = this;
            const loop = data => data.map((item) => {
                if (item.children) {
                    return <TreeNode title={<span onClick={()=>{this.onSelectTree(item)}}>{item.name}</span>} key={item.id}>{loop(item.children)}</TreeNode>;
                }
                return <TreeNode title={<span onClick={()=>{this.onSelectTree(item)}}>{item.name}</span>} key={item.id} isLeaf={item.isLeaf} dataApi={item.getLeafApi || ""} />;
            });
            const treeNodes = loop(this.state.hrmDatas);
             menu = <Menu>
                        <Tree loadData={this.onLoadData}  defaultExpandedKeys={["0"]}>
                            {treeNodes}
                        </Tree>
                </Menu>

        } ;
           
		return (
              <Dropdown  overlay={menu} trigger={['hover']} 
                    onVisibleChange={this.handleVisibleChange}
                     visible={this.state.visible}>
                       <Button type="ghost" style={{ marginLeft: 3 }} className="crm-tab-btn"> 
                             {value.indexOf("全部")===0 || value=="" ? defaultValue :value} <Icon type="down" />
                      </Button>
                </Dropdown>
        )
	}
    handleVisibleChange=(flag)=> {
        this.setState({ visible: flag });
    }
//     handleMenuClick(e) {
//         if (e.key !== 'calendar-header') {
//         this.setState({ visible: false });
//         }
//    }
    onMenuClick(e){
        const {selectKeys = ""} = this.props;
        if (e.key == 'important' || e.key == 'unimportant' ||e.key=="setting") {
           this.setState({ visible: false });
        }else{
            this.setState({visible:true})
        }
        if(e.key == 'important'){
            this.props.markTagsTo("1",selectKeys);
        }
        if(e.key == 'unimportant'){
            this.props.markTagsTo("0",selectKeys);
        }
   }
    markLable=(type)=>{
         const {selectKeys = ""} = this.props;
         const {checkArr} = this.state;
        if(type == "addLabel"){
            this.props.markToCustomTag(`${checkArr}`,selectKeys,"addLabel");
        }
        if(type == "cancelLabel"){
            this.props.markToCustomTag(`${checkArr}`,selectKeys,"cancelLabel");
        }

    }
    checkboxChange =(key) =>{
        let {checkArr } = this.state;
        const isExist =  this.in_arrary(checkArr,key);
        if(isExist != "false"){
            checkArr.splice(isExist,1);
        }else{
            checkArr.push(key)
        }
        this.setState({checkArr:checkArr})
    }
    in_arrary =(arr,key)=>{
        for(let i=0;i<arr.length ; i++){
            if(arr[i] == key){
                return i
            } 
        }
        return "false"
    }
    onSelectChange(e){
        const {keyValue=""} = this.props;
        const id = e.key == "item" ? "":e.key.replace("item","");
        this.setState({value:e.item.props.children,visible:false});
        let params = {};
        params[keyValue] = {name:keyValue,value:id}
        this.props.onChange(params);
    }
    onSelectTree=(item)=>{
        const {keyValue=""} = this.props;
        const id = item.id == "0" ? "":item.id;
        this.setState({value:item.name,visible:false});
        let params = {};
        params[keyValue] = {name:keyValue,value:id}
        this.props.onChange(params);
    }
    decYear=()=>{
        this.setState({thisyear:Number(this.state.thisyear)-1,visible:true})
    }
    addYear=()=>{
        this.setState({thisyear:Number(this.state.thisyear)+1,visible:true})
    }
    callBackMonth=(m)=>{
        const {keyValue=""} = this.props;
        const showMonth = this.state.thisyear+"-"+m;
        this.setState({value:showMonth,visible:false});
        let params = {};
        params[keyValue] = {name:keyValue,value:showMonth}
        this.props.onChange(params);
    }
    callBackMonthAll=()=>{
        const {keyValue=""} = this.props;
         this.setState({value:"",visible:false});
         let params = {};
         params[keyValue] = {name:keyValue,value:""}
         this.props.onChange(params);
    }
    setting=()=>{
        this.props.setting();
    }
    onLoadData=(treeNode)=>{
      
        const isChildren = treeNode.props.children || [];
        const that = this;
        if(!isChildren.length){
             return new Promise((resolve,reject) => {
                WeaTools.callApi(treeNode.props.dataApi, 'GET',{}).then((data)=>{
                    const childData = data.datas;
                    const treeData = [...that.state.hrmDatas];
                    const loop = (data) => {
                        data.forEach((item) => {
                            if (treeNode.props.eventKey.indexOf(item.id) === 0) {
                                item.children = childData;
                            }else if(item.children){
                                loop(item.children);
                            }
                        });
                    };
                    loop(treeData);
                     that.props.hrmListChange(treeData);   //回调，更新人员列表
                    that.setState({ num:that.state.num+1 });
                    resolve(data.datas);
                });
            })
        }else{
            return false;
        }
      
    }
}

export default WeaDropdown;